const app = getApp()

Page({
  data: {
    articleId: null,
    article: {},
    relatedArticles: [],
    isLiked: false,
    isCollected: false,
    loading: true
  },

  onLoad(options) {
    const articleId = options.id
    this.setData({ articleId })
    this.loadArticleDetail(articleId)
    this.loadRelatedArticles(articleId)
  },

  onShareAppMessage() {
    const { article } = this.data
    return {
      title: article.title,
      path: `/pages/article-detail/article-detail?id=${article.id}`,
      imageUrl: article.cover_image
    }
  },

  onShareTimeline() {
    const { article } = this.data
    return {
      title: article.title,
      imageUrl: article.cover_image
    }
  },

  // 加载文章详情
  loadArticleDetail(articleId) {
    wx.showLoading({ title: '加载中...' })

    wx.request({
      url: `${app.globalData.baseUrl}/articles/${articleId}`,
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          const article = res.data.data
          
          // 格式化时间
          article.created_at = this.formatDate(article.created_at)
          
          this.setData({ 
            article,
            loading: false
          })

          // 设置页面标题
          wx.setNavigationBarTitle({
            title: article.title
          })

          // 增加阅读量
          this.increaseViewCount(articleId)
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载文章详情失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 加载相关文章
  loadRelatedArticles(articleId) {
    wx.request({
      url: `${app.globalData.baseUrl}/articles/`,
      method: 'GET',
      data: {
        page: 1,
        per_page: 3,
        exclude_id: articleId
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            relatedArticles: res.data.data.items
          })
        }
      },
      fail: (err) => {
        console.error('加载相关文章失败:', err)
      }
    })
  },

  // 增加阅读量
  increaseViewCount(articleId) {
    wx.request({
      url: `${app.globalData.baseUrl}/articles/${articleId}/view`,
      method: 'POST',
      fail: (err) => {
        console.error('增加阅读量失败:', err)
      }
    })
  },

  // 格式化日期
  formatDate(dateString) {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now - date
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚'
    }
    
    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    }
    
    // 小于24小时
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    }
    
    // 小于30天
    if (diff < 2592000000) {
      return `${Math.floor(diff / 86400000)}天前`
    }
    
    // 超过30天显示具体日期
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  },

  // 跳转到其他文章
  goToArticle(e) {
    const articleId = e.currentTarget.dataset.id
    wx.redirectTo({
      url: `/pages/article-detail/article-detail?id=${articleId}`
    })
  },

  // 分享文章
  shareArticle() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  // 点赞文章
  likeArticle() {
    const { articleId, isLiked } = this.data
    
    if (isLiked) {
      wx.showToast({
        title: '已经点赞过了',
        icon: 'none'
      })
      return
    }

    wx.request({
      url: `${app.globalData.baseUrl}/articles/${articleId}/like`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ isLiked: true })
          wx.showToast({
            title: '点赞成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message || '点赞失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('点赞失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  // 收藏文章
  collectArticle() {
    const { articleId, isCollected } = this.data
    
    if (isCollected) {
      wx.showToast({
        title: '已经收藏过了',
        icon: 'none'
      })
      return
    }

    wx.request({
      url: `${app.globalData.baseUrl}/articles/${articleId}/collect`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ isCollected: true })
          wx.showToast({
            title: '收藏成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message || '收藏失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('收藏失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  }
}) 